package com.zmn.oms.api.controller.order;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.PageResultDTO;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.enums.EncryptFieldTypeEnum;
import com.zmn.oms.model.entity.work.OrderWorkOperateQuery;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.model.vo.call.CallOrderVO;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 类描述：订单查询
 *
 * @author lujia
 * @date 2019/01/22 20:11
 */
@RestController
@RequestMapping("/call/order")
@Slf4j
public class CallOrderController {

    @Autowired
    private OrderWorkListBService orderWorkListBService;
    @Autowired
    private OrderEncryptService orderEncryptService;

    @GetMapping("/ajax/list")
    public ResultDTO listByOpenId(@RequestParam String phones,
                                  @RequestParam String receiverTime,
                                  @RequestParam(required = false) Integer receiverId,
                                  @RequestParam String auth){

        // 参数校验
        if (!GlobalConsts.AUTH_INFO.equals(auth)) {
            return ResultDTO.fail("auth fail");
        }

        String[] phoneList = phones.split(",");

        OrderWorkQuery query = new OrderWorkQuery();
        query.setWorkType(Lists.newArrayList(OrderConsts.ORDER_TYPE_REWORK, OrderConsts.ORDER_TYPE_NEW));
        query.setConcatPhoneList(Lists.newArrayList(phoneList));
        query.setReceiveTime(receiverTime);

        if (receiverId != null) {
            OrderWorkOperateQuery operateQuery = new OrderWorkOperateQuery();
            operateQuery.setOperateType(OrderConsts.ORDER_OP_TYPE_INPUT);
            operateQuery.setOperatorId(receiverId);
            query.setOperate(operateQuery);
        }

        query.setPageSize(1000);
        query.setPageIndex(1);
        query.setOrderField("receiveTime");

        // 字段白名单
        query.setIncludes(Arrays.asList("receiveTime", "id", "cityId", "servCategId", "servCategName", "resultStatus",
                "resultStatusName", "contact.phone", "status", "statusName"));

        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
        // 解密电话
        orderEncryptService.batchDecryptEsOrderWork(esOrderWorkList, EncryptFieldTypeEnum.USER_TELPHONE);
        Map<String, EsOrderWork> workMap = Maps.newHashMap();
        for (String phone : phoneList) {
            if (!workMap.containsKey(phone)) {
                Optional<EsOrderWork> first = esOrderWorkList.stream().filter(e -> Lists.newArrayList(e.getContact().getPhone()).contains(phone)).findFirst();
                if (first.isPresent()) {
                    EsOrderWork esOrderWork = first.get();
                    workMap.put(phone, esOrderWork);
                }
            }
        }

        return ResultDTO.success(workMap);
    }

    /**
     * 按接单时间查询工单
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param pageIndex 页码
     * @param pageSize 每页大小
     * @param auth 鉴权
     * @return
     */
    @GetMapping("/ajax/receivetime/list")
    public ResultDTO listByReceiveTime(@RequestParam(defaultValue = "") String startTime,
                               @RequestParam(defaultValue = "") String endTime,
                               @RequestParam(required = false,defaultValue = "1") Integer pageIndex,
                               @RequestParam(required = false,defaultValue = "50") Integer pageSize,
                               @RequestParam String auth) {

        // 参数校验
        if (!GlobalConsts.AUTH_INFO.equals(auth)) {
            return ResultDTO.fail("auth fail");
        }

        // 查询
        OrderWorkQuery query = new OrderWorkQuery();
        query.setIncludes(Arrays.asList("id", "orderId", "platWork", "cityId", "contact.phone", "bizType", "receiveTime"));

        query.setReceiveTime(startTime + "," + endTime);
        query.setPageSize(pageSize);
        query.setPageIndex(pageIndex);
        query.setOrderField("receiveTime");
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);

        // 转换
        List<CallOrderVO> list = Lists.newArrayList();
        esOrderWorkList.forEach(e->{
            CallOrderVO callOrderVO = new CallOrderVO();
            callOrderVO.setWorkId(e.getId());
            callOrderVO.setOrderId(e.getOrderId());
            callOrderVO.setPlatMark(e.getPlatWork());
            if (e.getContact() != null && e.getContact().getPhone() != null) {
                String[] phone = e.getContact().getPhone();
                callOrderVO.setTelephone(phone[0]);
                callOrderVO.setTelephone2(phone.length > 1 ? phone[1] : "");
                callOrderVO.setTelephone3(phone.length > 2 ? phone[2] : "");
            }
            callOrderVO.setCityId(e.getCityId());
            callOrderVO.setBizType(e.getBizType());
            callOrderVO.setCreateTime(e.getReceiveTime() != null ? DateUtil.toString(e.getReceiveTime()) : "");
            list.add(callOrderVO);
        });

        return PageResultDTO.success(list, query.getTotalCount());
    }
}
